package juc.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author fangbin
 * @desc  演示非公平锁，读锁可以插队(前提是队头是读锁)，如果对头是写锁，不允许插队
 * @date 2020/6/11 20:25
 */
public class NonFairBargeDemo {

    public static ReentrantReadWriteLock reentrantReadWriteLock =
            new ReentrantReadWriteLock(false);

    public static ReentrantReadWriteLock.ReadLock readLock =
            reentrantReadWriteLock.readLock();
    public static ReentrantReadWriteLock.WriteLock writeLock =
            reentrantReadWriteLock.writeLock();

    public static  void read(){
        System.out.println(Thread.currentThread().getName()+"尝试获取读锁");
        try{
            readLock.lock();
            System.out.println(Thread.currentThread().getName()+"得到锁，正在读取");
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放读锁");
            readLock.unlock();
        }
    }
    public static  void write(){
        System.out.println(Thread.currentThread().getName()+"尝试获取写锁");
        try{

            writeLock.lock();
            System.out.println(Thread.currentThread().getName()+"得到锁，正在写入");
            Thread.sleep(40);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放写锁");
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        new Thread(()->write(),"Thread1").start();
        new Thread(()->read(),"Thread2").start();
        new Thread(()->read(),"Thread3").start(); //Thread3获取到锁后，下面就是写锁了，然后就不允许插队
        new Thread(()->write(),"Thread4").start();
        new Thread(()->read(),"Thread5").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Thread[] threads = new Thread[1000];
                for(int i=0;i<1000;i++){
                    threads[i] = new Thread(()->read(),"子线程创建的Thread"+i);
                }
                for(int i=0;i<1000;i++){
                    threads[i].start();
                }
            }
        }).start();
    }
}
